import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class TextCanvasCalcDart extends StatefulWidget {
  const TextCanvasCalcDart({super.key});

  @override
  State<TextCanvasCalcDart> createState() => _TextCanvasCalcDartState();
}

class _TextCanvasCalcDartState extends State<TextCanvasCalcDart> {
  double width = 100;

  final controller = TextEditingController(text: "测试一下文字的宽度");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("TextCanvasCalcDart"),
      ),
      body: Column(
        children: [
          CupertinoTextField(
            controller: controller,
            placeholder: "请输入",
            onChanged: (value) {
              setState(() {});
            },
          ),
          Text('maxWidth: $width'),
          Slider(
            value: width,
            min: 100,
            max: 400,
            divisions: 600,
            onChanged: (value) {
              setState(() {
                width = value;
              });
            },
          ),
          ExampleContainer(
            width: width,
            text: controller.text,
          ),
          CalcText(
            width: width,
            text: controller.text,
          ),
        ],
      ),
    );
  }
}

class ExampleContainer extends StatelessWidget {
  const ExampleContainer({super.key, required this.text, required this.width});

  final String text;
  final double width;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      color: Colors.red,
      child: Text(text),
    );
  }
}

class CalcText extends StatelessWidget {
  const CalcText({
    super.key,
    required this.text,
    required this.width,
  });

  final String text;
  final double width;

  @override
  Widget build(BuildContext context) {
    final painter = TextPainter(
      text: TextSpan(
        text: text,
        style: const TextStyle(fontSize: 14),
      ),
      textDirection: TextDirection.ltr,
    );
    painter.layout(minWidth: 0, maxWidth: width);
    final line = painter.computeLineMetrics();
    final paintWidth = painter.width;
    final paintHeight = painter.height;
    return Text(
      'width: $paintWidth \n height: $paintHeight \n line: ${line.length}',
    );
  }
}
